home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 15766 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.4 KB

  1. Path: hubcap.clemson.edu!hubcap!mjs
  2. From: mjs@hubcap.clemson.edu (M. J. Saltzman)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: help rand !
  5. Date: 19 Apr 96 15:03:59 GMT
  6. Organization: Clemson University
  7. Message-ID: <mjs.829926239@hubcap>
  8. References: <4l5d75$mes@usenetp1.news.prodigy.com> <4l5fj4$1ehs@serra.unipi.it> <4l5vjm$5lj@ccshst05.uoguelph.ca> <4l7bnt$r44@griffin.itc.gu.edu.au>
  9. NNTP-Posting-Host: hubcap.clemson.edu
  10. X-Newsreader: NN version 6.5.0 #1
  11.  
  12. Student (Student) writes:
  13.  
  14. |I assume you want something that does this:
  15. |10 random -> 9,3,5,1,7,8,2,4,10,6
  16. |You could consider creating an array n[n]
  17.                                       ^^^^One of these things needs to be
  18.                       called something else.
  19. |where n represents the highest number
  20. |and then just randomly swaping the contents for every n.
  21. |ie: before:    n[1] = 1
  22. |        n[2] = 2
  23. |          :    :
  24. |        n[10]=10
  25.  
  26. Of course, in comp.lang.c, we index our arrays from 0 to n-1:
  27. ie: before:    n[0] = 0
  28.         n[2] = 2
  29.           :    :
  30.         n[9] = 9
  31.  
  32. |swap n[1] with n[rand]
  33. |swap n[2] with n[rand]
  34. |......................
  35. |swap n[10] with n[rand]
  36. |    
  37. |after:        n[1] = 9
  38. |        n[2] = 3
  39. |          :    :
  40. |        n[10]= 6
  41.  
  42. |This ain't that great, but it will work predictably.
  43.  
  44. It will work better if you make sure that the random index rand lies
  45. between the current index and the end of the array (inclusive).  If
  46. you take any random index then the permutations are not all equally 
  47. likely.
  48. -- 
  49.         Matthew Saltzman
  50.         Clemson University Math Sciences
  51.         mjs@clemson.edu
  52.